package com.kaikeba.t31ticket.ticket.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kaikeba.t31ticket.ticket.entity.CarriageEntity;
import com.kaikeba.t31ticket.ticket.entity.TicketTemplateEntity;
import com.kaikeba.t31ticket.ticket.entity.TrainSeatEntity;
import com.kaikeba.t31ticket.ticket.service.CarriageService;
import com.kaikeba.t31ticket.ticket.service.TicketTemplateService;
import com.kaikeba.t31ticket.ticket.service.TrainSeatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class GenerateTicketTemplate {
    @Autowired
    private CarriageService carriageService;

    @Autowired
    private TrainSeatService trainSeatService;

    @Autowired
    private TicketTemplateService ticketTemplateService;

    /**
     * 找到所有的座位
     */
    public List<CarriageEntity> findAllCarriage() {
        return carriageService.list();
    }

    /**
     * 找到所有的车厢
     */
    public List<TrainSeatEntity> findAllTrainSeat() {
        return trainSeatService.list();
    }

    /**
     * 生成所以的 seat template
     */
    public List<TicketTemplateEntity> generateTicketTemplate() {
        List<CarriageEntity> carriageEntityList = this.findAllCarriage();
        List<TrainSeatEntity> trainSeatEntityList = this.findAllTrainSeat();
        List<TicketTemplateEntity> ticketTemplateEntityList = new ArrayList<>();

        carriageEntityList.stream().forEach(carriageEntity -> trainSeatEntityList.stream().allMatch(trainSeatEntity -> {
            if (trainSeatEntity.getCarriageId().equals(carriageEntity.getId())) {
                TicketTemplateEntity ticketTemplateEntity = new TicketTemplateEntity();
                ticketTemplateEntity.setCarriageId(trainSeatEntity.getCarriageId());
                ticketTemplateEntity.setCarriageNumber(carriageEntity.getCarriageNumber());
                ticketTemplateEntity.setSeatId(trainSeatEntity.getId());
                ticketTemplateEntityList.add(ticketTemplateEntity);
            }
            return true;
        }));
        return ticketTemplateEntityList;
    }

    /**
     * 将所有的 seat template 存到 DB 中
     */
    public void saveTicketTemplates() {
        List<TicketTemplateEntity> ticketTemplateEntityList = this.generateTicketTemplate();
        ticketTemplateService.saveBatch(ticketTemplateEntityList);
    }
}
